package com.namo.cchtool.controller;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.namo.cchcommon.api.CommonResult;
import com.namo.cchtool.entity.Contact;
import com.namo.cchtool.service.ContactService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Locale;

import static cn.hutool.extra.pinyin.PinyinUtil.getFirstLetter;

/**
 * @author WangXin
 * @date 2021/5/17 11:14
 */
@RestController
@RequestMapping("/contact")
public class ContactController {

    @Autowired
    ContactService contactService;

    @Autowired
    Gson gson;

    @RequestMapping(value = "/all",method = RequestMethod.GET)
    public CommonResult getAllContact(){
        List<Contact> contacts =contactService.getAllContact();
            //查询到的对象转换为JsonArray
        JsonArray jsonArray = gson.fromJson(gson.toJson(contacts), JsonArray.class);
        for (int i = 0; i < jsonArray.size(); i++) {
            //从JsonArray中获得单个数组对象的name
            String objectName = jsonArray.get(i).getAsJsonObject().get("name").getAsString();
            //获取字符串的每个子的首字母，再转大写，截取得到第一个字符
            Character ch = getFirstLetter(objectName, ",").toUpperCase(Locale.ROOT).charAt(0);
            //插入单个对象的index属性，属性值为name的首字母
            jsonArray.get(i).getAsJsonObject().addProperty("index",ch);
        }
        return CommonResult.success(gson.fromJson(jsonArray,Object.class));
    }
}
